var Node = {
   ELEMENT_NODE: 1
}

function App() {

}

App.prototype.init = function() {
   this.zoom = 100;
   this.buildUI();
   this.loadData();
   this.changeSlide();
}

App.prototype.loadData = function() {
   this.unordered = 10000;
   this.slides = [];
   var option = this.toc.firstChild;
   while (option) {
      var e = option;
      option = option.nextSibling;
      e.parentNode.removeChild(e);
   }
   var head = document.documentElement.firstChild;
   while (head && head.nodeType!=Node.ELEMENT_NODE && head.localName!="head") {
      head = head.nextSibling;
   }
   try {
      var entry = _helper.document.documentElement.firstChild;
      while (entry) {
         if (entry.nodeType==Node.ELEMENT_NODE && entry.localName=="entry" && entry.namespaceURI=="http://www.w3.org/2005/Atom") {
            if (this.getCategories(entry, "slide").length>0) {
               this.addSlide(entry);
            }
            if (this.getCategories(entry, "style").length>0) {
               var content = this.getChildren(entry,"content");
               if (content.length>0) {
                  var src = content[0].getAttribute("src");
                  var type = content[0].getAttribute("type");
                  var link = document.createElement("link");
                  link.setAttribute("rel","stylesheet");
                  link.setAttribute("type",type);
                  link.setAttribute("href",src);
                  head.appendChild(link);
               }
            }
         }
         entry = entry.nextSibling;
      }
      this.slides.sort(function(a,b) {
         return a.order-b.order;
      });

      this.loadTOC();


   } catch (ex) {
      alert(ex);
   }
}

App.prototype.buildUI = function () {
   var current = this;

   this.controls = document.createElement("div");
   this.controls.setAttribute("id","-app-controls");
   document.body.appendChild(this.controls);
   this.controls.style.display = "none";

   var nav = document.createElement("div");
   this.controls.appendChild(nav);
   nav.className = "-app-nav";

   this.prevButton = document.createElement("button");
   Console.log(document);
   this.prevButton.onclick = function() {
      current.onPrevious();
   }
   this.prevButton.appendChild(document.createTextNode("Previous"));
   nav.appendChild(this.prevButton);

   this.toc = document.createElement("select");
   this.toc.setAttribute("id","-app-toc");
   nav.appendChild(this.toc);

   this.nextButton = document.createElement("button");
   this.nextButton.onclick = function() {
      current.onNext();
   }
   this.nextButton.appendChild(document.createTextNode("Next"));
   nav.appendChild(this.nextButton);

   this.sizes = document.createElement("select");
   this.sizes.setAttribute("id","-app-sizes");
   this.controls.appendChild(this.sizes);
   var internalSizes = [ [ 1024, 768], [1152, 720], [1280, 800], [1440, 900]]
   for (var i=0; i<internalSizes.length; i++) {
      var option = document.createElement("option");
      option.setAttribute("value",internalSizes[i][0]+","+internalSizes[i][1]);
      option.appendChild(document.createTextNode(internalSizes[i][0]+" x "+internalSizes[i][1]));
      this.sizes.appendChild(option);
   }

   this.sizes.onchange = function() {
      var value = current.sizes.options[current.sizes.selectedIndex].value;
      var comma = value.indexOf(",");
      var width = parseInt(value.substring(0,comma));
      var height = parseInt(value.substring(comma+1));
      current.changeSize(width,height);
   }

   this.content = document.createElement("div");
   this.content.setAttribute("id","-app-content");
   document.body.appendChild(this.content);

   this.toc.onchange = function() {
      current.changeSlide();
   };

   window.addEventListener('resize',function() {
      current.onResize();
   },false);
   this.onResize();

   window.addEventListener('keypress',function(event) {
      switch (event.keyCode) {
         case 37:
            current.onPrevious();
            break;
         case 39:
            current.onNext();
      }
      switch (event.charCode) {
         case 32:
            current.onNext();
            break;
         case 48:
            current.zoom = 100;
            current.applyZoom(100);
            break;
         case 90: //'Z'
            current.onZoomIncrement();
            break;
         case 109: //'m'
            if (current.controls.style.display=="block") {
               current.controls.style.display = "none";
            } else {
               current.controls.style.display = "block";
            }
            break;
         case 115: //'s'
            current.toc.selectedIndex = 0;
            current.changeSlide();
            break;
         case 122: //'z'
            current.onZoomDecrement();
            break;
      }
      //alert(event.keyCode+" "+event.charCode);
   },false)
   this.changeSize(internalSizes[0][0],internalSizes[0][1]);

}

App.prototype.onZoomIncrement = function() {
   this.zoom++;
   this.applyZoom();
}

App.prototype.onZoomDecrement = function() {
   this.zoom++;
   this.applyZoom();
}

App.prototype.applyZoom = function() {
   this.content.style.zoom = this.zoom+"%";
}

App.prototype.changeSize = function(width,height) {
   this.content.style.height = (height-50)+"px";
   this.content.style.width = (width-30)+"px";
}

App.prototype.onPrevious = function() {
   if (this.toc.selectedIndex>0) {
      this.toc.selectedIndex--;
      this.changeSlide();
   }

}
App.prototype.onNext = function() {
   if (this.toc.selectedIndex<(this.slides.length-1)) {
      this.toc.selectedIndex++;
      this.changeSlide();
   }
}
App.prototype.onResize = function() {
   this.controls.style.top = (window.innerHeight-33)+"px";
   this.controls.style.width = (window.innerWidth-10)+"px";
}

App.prototype.getCategories = function(element,term,scheme) {
   var categories = [];
   for (var i=0; i<element.childNodes.length; i++) {
      var current = element.childNodes[i];
      if (current.nodeType==Node.ELEMENT_NODE && current.localName=="category" && current.namespaceURI=="http://www.w3.org/2005/Atom") {
         if ((!term || current.getAttribute("term")==term) &&
             (!scheme || current.getAttribute("scheme")==scheme)) {
            categories.push({ element: current, value: current.textContent, term: current.getAttribute("term"), scheme: current.getAttribute("scheme")});
         }
      }
   }
   return categories;
}

App.prototype.getChildren = function(element,name) {
   var elements = [];
   var current = element.firstChild;
   while (current) {
      if (current.nodeType==Node.ELEMENT_NODE && current.localName==name && current.namespaceURI=="http://www.w3.org/2005/Atom") {
         elements.push(current);
      }
      current = current.nextSibling;
   }
   return elements;
}

App.prototype.addSlide = function(element) {
   var orders = this.getCategories(element,"order");
   var order = orders.length>0 ? parseInt(orders[0].value) : this.unordered++;
   var titles = this.getChildren(element,"title");
   var content = this.getChildren(element,"content");
   this.slides.push({
      order: order,
      element: element,
      title: titles.length>0 ? titles[0].textContent : "",
      content: content.length>0 ?  content[0] : null,
      layouts: this.getCategories(element,"layout")
   });
}

App.prototype.loadTOC = function() {
   for (var i=0; i<this.slides.length; i++) {
      var title = this.getChildren(this.slides[i].element,"title")[0].textContent;
      var option = document.createElement("option");
      this.toc.appendChild(option);
      option.appendChild(document.createTextNode(title));
      option.setAttribute("value",""+i);
   }
}

App.prototype.changeSlide = function(noretry) {
   try {
   if (this.toc.selectedIndex==0) {
      this.nextButton.disabled = false;
      this.prevButton.disabled = true;
   } else if (this.toc.selectedIndex==(this.slides.length-1)) {
      this.nextButton.disabled = true;
      this.prevButton.disabled = false;
   } else {
      this.nextButton.disabled = false;
      this.prevButton.disabled = false;
   }

   this.clearContent();

   var slide = this.slides[this.toc.selectedIndex];

   var heading = document.createElement("h1");
   heading.appendChild(document.createTextNode(slide.title));
   this.content.appendChild(heading);

   var slideBody = document.createElement("div");
   this.content.appendChild(slideBody);
   slideBody.className = "body";

   var layout = "";
   for (var i=0; i<slide.layouts.length; i++) {
      layout += slide.layouts[i].value;
      layout += " ";
   }
   this.content.className = layout;

   var content = this.getChildren(this.slides[this.toc.selectedIndex].element,"content");
   if (content.length>0) {
      var child = content[0].firstChild;
      while (child && child.nodeType!=Node.ELEMENT_NODE) {
         child = child.nextSibling;
      }
      if (child) {
         this.addSlideContent(slideBody,child);
      }
   }
   } catch (ex) {
      alert(ex);
   }
}

App.prototype.clearContent = function() {
   var current = this.content.firstChild;
   while (current) {
      var e = current;
      current = current.nextSibling;
      e.parentNode.removeChild(e);
   }
}

App.prototype.addSlideContent = function(parent,node) {
   var fragment = _helper.importNode(document, node);
   var current = fragment.firstChild;
   while (current) {
      parent.appendChild(current);
      current = current.nextSibling;
   }
}


Console.log("Initializing slides application.");

var app = new App();
app.init();      
